import Loading from './components/loading.vue';
import { render, defineComponent, h, createVNode } from 'vue';
let tip = '';
// 组件
const loadingWrap = defineComponent({
    render() {
        return h(Loading, {
            tip, loading: true
        });
    }
});
const dom = h(Loading, {
    tip, loading: true
});
// console.log('dom', dom)

const toggleLoading = (el, binding) => {
    if (!el.getAttribute) {
        return;
    }
    tip = el?.getAttribute('loading-tip') || '';
    if (binding.value) {
        const vdom = createVNode(Loading, {
            tip, loading: true, fullScreen: el?.getAttribute('loading-fullscreen')
        });
        // const vdom = createVNode(loadingWrap);
        let container = undefined;
        container = (document as any).createElement('div');
        container && render(vdom, container);
        // console.log(vm.el)
        // 为了防止多次重复添加同一子节点
        if (el.container) {
            if (el.container.parentNode === el) {
                return;
            }
        }
        el.appendChild(container);
        el.vm = vdom;
        el.container = container;
        // nextTick(() => {
        //     (el.vm as any).component.ctx.open();
        // });
    } else {
        if (el.container) {
            // (el.vm as any).component.ctx.close();
            if (el.container.parentNode) {
                el.container.parentNode.removeChild(el.container);
            }
        }
    }
};
const vLoading = {
    // 当被绑定的元素挂载到 DOM 中时……
    mounted(el: any, binding: any) {
        if (!el.getAttribute) {
            return;
        }
        const fullscreen = el?.getAttribute('loading-fullscreen');
        el = fullscreen ? document.body : el;
        toggleLoading(el, binding);
    },
    updated(el: any, binding: any) {
        if (!el.getAttribute) {
            return;
        }
        const fullscreen = el?.getAttribute('loading-fullscreen');
        el = fullscreen ? document.body : el;
        toggleLoading(el, binding);
    }
};

export const setupLoadingDirective = (app: any) => {
    app.directive('loading', vLoading);
};